<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
			<uni-forms-item name="behavior" label="行为" required>
				<uni-easyinput placeholder="做了什么行为" v-model="formData.behavior" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="emission_reduction" label="当日减排量" required>
				<uni-easyinput placeholder="当日减排量" type="number" v-model="formData.emission_reduction"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/abu_CarbonRecord.js';

	const db = uniCloud.database();
	const dbCollectionName = 'abu_CarbonRecord';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"behavior": "",
				"emission_reduction": null
			}
			return {
				current_user_info: {},
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad() {
			this.current_user_info = uniCloud.getCurrentUserInfo()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					title: '记载中',
					mask: false
				});
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			init_user_score(value) {
				// 查询当前用户的余额
				const userRef = db.collection('uni-id-scores').where({
					user_id: this.current_user_info.uid
				}).orderBy("balance").get().then(snapshot => {
					// console.log(snapshot.result.data);
					let currentBalance = 0;
					if (snapshot.result.data.length !== 0) {
						currentBalance = snapshot.result.data[0].balance;
					}
					db.collection("uni-id-scores").add({
						"user_id": this.current_user_info.uid,
						"score": value.emission_reduction,
						"type": 1,
						"balance": currentBalance + value.emission_reduction,
						"comment": value.behavior,
					});
					// }
				}).catch(error => {
					console.error('Error getting user document:', error);
				});
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				this.init_user_score(value)
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						icon: 'none',
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
					// uni.navigateBack()
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}
</style>